package com.xy.shop.wechat.controller;

import com.xy.shop.wechat.service.BaseWxService;
import com.xy.shop.wechat.service.Gzh1WxService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 第一个公众号的微信交互接口
 *
 * @author Binary Wang
 */
@Controller
@RequestMapping("/")
public class Gzh1WxPortalController extends AbstractWxPortalController {
  
  @Resource
  private Gzh1WxService wxService;


  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @RequestMapping(value = "/wechat/test", method = RequestMethod.GET)
  public void authGet() {
    this.logger.info("\n接收到来自微信服务器的认证消息：[{},{},{},{}]");
    this.logger.debug("\n接收到来自微信服务器的认证消息：[{},{},{},{}]");
  }
  @Override
  @RequestMapping(value="/wechat/portal/qshd",method = RequestMethod.GET )
  public void authGet(@RequestParam(name = "signature", required = false) String signature, HttpServletResponse response,
                      @RequestParam(name = "timestamp", required = false) String timestamp,
                      @RequestParam(name = "nonce", required = false) String nonce,
                      @RequestParam(name = "echostr", required = false) String echostr) throws IOException {
    this.logger.info("\n接收到来自微信服务器的认证消息：[{},{},{},{}]", signature, timestamp, nonce, echostr);
    this.logger.debug("\n接收到来自微信服务器的认证消息：[{},{},{},{}]", signature, timestamp, nonce, echostr);

    if (this.getWxService().checkSignature(timestamp, nonce, signature)) {
    	PrintWriter out = response.getWriter();
    	out.print(echostr); 
    }

  }

 
  @Override
  @ResponseBody
  @RequestMapping(value="/wechat/portal/qshd",method = RequestMethod.POST)
  public String post(@RequestBody String requestBody, @RequestParam("signature") String signature,
                     @RequestParam(name = "encrypt_type", required = false) String encType,
                     @RequestParam(name = "msg_signature", required = false) String msgSignature,
                     @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce) {
    this.logger.info(
        "\n接收微信请求：[signature=[{}], encType=[{}], msgSignature=[{}],"
            + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
        signature, encType, msgSignature, timestamp, nonce, requestBody);

    if (!this.getWxService().checkSignature(timestamp, nonce, signature)) {
      throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
    }

    String out = null;
    if (encType == null) {
      // 明文传输的消息
      WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
      WxMpXmlOutMessage outMessage = this.getWxService().route(inMessage);
      if (outMessage == null) {
        return "";
      }
      out = outMessage.toXml();
    } else if ("aes".equals(encType)) {
      // aes加密的消息
      WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody,
          this.getWxService().getWxMpConfigStorage(), timestamp, nonce, msgSignature);
      this.logger.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
      WxMpXmlOutMessage outMessage = this.getWxService().route(inMessage);
      if (outMessage == null) {
        return "";
      }

      out = outMessage.toEncryptedXml(this.getWxService().getWxMpConfigStorage());
    }

    this.logger.debug("\n组装回复信息：{}", out);

    return out;
  }


  @Override
  protected BaseWxService getWxService() {
    return this.wxService;
  }

}
